import React, { useState, useEffect } from 'react';
import { connect, Dispatch } from 'umi';
import { message, Space, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import { API_INIT, API_LIST, API_ADD, API_UPDATE, API_DELETE, API_UNMOUNT } from '@/actions/api';
import { ConnectState } from '@/models/connect';
import { ApiItem, ApiSelectTreeItem } from '@/types/api';
import { DataItem, FlagEnum } from '@/types/global';
import { getItemValue } from '@/utils/commons';
import ApiQueryForm from './components/ApiQueryForm';
import AddApiModal from './components/AddApiModal';
import UpdateApiModal from './components/UpdateApiModal';

type ApiListProps = {
  dispatch: Dispatch;
  apiList: ApiItem[],
  total: number,
  loading: boolean;
  pageSize: number;
  addLoading: boolean;
  updateLoading: boolean;
  apiTypeData: DataItem[];
  statusData: DataItem[];
}

const EMPTY: ApiItem = {
  apiId: '',
  parentApiId: '',
  apiCode: '',
  apiName: '',
  apiUrl: '',
  apiType: '',
  apiStates: '',
  apiSort: '',
  apiAlias: '',
  children: []
}

const ApiList: React.FC<ApiListProps> = (props) => {
  // 新增弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  const [apiFormData, setApiFormData] = useState<ApiItem>(EMPTY);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<ApiItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParam, setQueryParam] = useState<ApiItem>();
  const [flag, setFlag] = useState<FlagEnum>('edit');

  useEffect(() => {
    console.info('ApiList.useEffect');
    // 查询本页面需所有参数
    const { dispatch } = props;
    dispatch(API_INIT({}));
    return () => {
      dispatch(API_UNMOUNT({}));
    }
  }, []);

  const columns: ColumnsType<ApiItem> = [
    {
      title: '接口权限名称',
      dataIndex: 'apiName',
      width: 200,
      ellipsis: true
    },
    {
      title: '接口权限图标',
      dataIndex: 'apiIcon',
      width: 180,
      ellipsis: true
    },
    {
      title: '接口权限编号',
      dataIndex: 'apiCode',
      width: 130
    },
    {
      title: '接口权限类型',
      dataIndex: 'apiType',
      render: (text: string, record: ApiItem, index: number) => apiTypeFunc(record),
      width: 80
    },
    {
      title: '接口url',
      dataIndex: 'apiUrl',
      width: 220,
      ellipsis: true
    },
    {
      title: '接口权限别名',
      dataIndex: 'apiAlias',
      width: 180
    },
    {
      title: '排序',
      dataIndex: 'apiSort',
      width: 60
    }
  ];
  
  const apiTypeFunc = (record: ApiItem) => {
    const { apiTypeData } = props;
    const { apiType } = record;
    const value = getItemValue(apiTypeData, apiType);
    if (apiType === '2' || apiType === '4') {
      return <Tag color='error'>{value}</Tag>;
    }
    return <Tag color='processing'>{value}</Tag>;
  }

  /**
   * 打开接口权限新增窗口
   */
  const openAddApiModal = () => {
    if (selectedRowKeys && selectedRowKeys.length == 1) {
      // 把勾选的节点当上级节点
      // 判断是否为菜单或弹窗
      const row = selectedRows[0];
      setApiFormData({
        ...row
      });
    }
    setAddModalVisible(true);
  }

  /**
   * 修改接口权限，打开接口权限修改窗口
   */
  const openUpdateApiModal = (record: ApiItem[], flag: FlagEnum) => {
    // 表格选中内容
    console.info('openUpdateApiModal');
    console.info(record);
    const row = record[0];
    const apiFormData: ApiItem = {
      ...row,
    };
    setApiFormData(apiFormData);
    setFlag(flag);
    setUpdateModalVisible(true);
  }

  const handleAddModalOk = async (record: ApiItem) => {
    console.log(record);
    const { dispatch } = props;
    const res = await dispatch(API_ADD(record));
    console.info(res);
    if (res) {
      setAddModalVisible(false);
      setApiFormData(EMPTY);
      const { pageSize } = props;
      fetchAllApi(1, pageSize);
    }
  }

  const handleAddModalCancel = () => {
    setAddModalVisible(false);
    setApiFormData(EMPTY);
  };

  const handleUpdateModalOk = async (record: ApiItem) => {
    console.log('handleUpdateModalOk');
    console.log(record);
    if (flag === 'edit') {
      const { dispatch } = props;
      const res = await dispatch(API_UPDATE(record));
      console.info(res);
      if (res) {
        setUpdateModalVisible(false);
        setApiFormData(EMPTY);
        const { pageSize } = props;
        fetchAllApi(1, pageSize);
      }
    } else {
      setUpdateModalVisible(false);
      setApiFormData(EMPTY);
    }
  }

  const handleUpdateModalCancel = () => {
    setUpdateModalVisible(false);
    setApiFormData(EMPTY);
  };

  const deleteApis = async (keys:React.Key[]) => {
    const { dispatch } = props;
    const res = await dispatch(API_DELETE(keys));
    if (res) {
      const { pageSize } = props;
      fetchAllApi(1, pageSize);
    }
  }

  /**
   * 根据条件分页查询表格数据
   * @param {*} record 条件
   */
  const handleFetchApi = (record: ApiItem) => {
    console.log(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    setQueryParam(queryParam);
    const { pageSize } = props;
    fetchAllApi(1, pageSize);
  }

  /**
   * 查询接口权限树信息
   * @param {*} pageSize 每页记录条数
   * @param {*} pageNum 页码
   */
  const fetchAllApi = (pageNum: number, pageSize: number) => {
    const { dispatch } = props;
    dispatch(API_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<ApiItem>) => {
    // btn 按钮
    // keys 表格勾选数组
    const { code, keys } = callBackModel;
    // 新增
    if (code === 'add') {
      openAddApiModal();
      return;
    }
    // 修改
    if (code === 'edit') {
      const { rows } = callBackModel;
      openUpdateApiModal(rows, 'edit');
      return;
    }
    // 删除
    if (code === 'delete') {
      const { rows } = callBackModel;
      let flag = false;
      for (let index = 0; index < rows.length; index++) {
        const row = rows[index];
        const { apiType } = row;
        if (apiType !== '4') {
          flag = true;
        }
      }
      if (flag) {
        message.warn('请在菜单权限管理页面删除菜单和按钮');
        return;
      }
      // 调用删除服务，删除勾选数据
      deleteApis(keys);
      return;
    }
    // 查看
    if (code === 'view') {
      const { rows } = callBackModel;
      openUpdateApiModal(rows, 'view');
      return;
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: ApiItem[]) => {
    setSelectedRows(rows);
    setSelectedRowKeys(keys);
  };

  /**
   * 根据全量接口权限数据生成下拉框接口权限树形数据，过滤掉按钮
   * @param {Array} apiList 全量接口权限数据
   * @returns 下拉框接口权限树形数据
   */
  const generatorApiTreeData = (apiList: ApiItem[] = []): ApiSelectTreeItem[] => {
    return apiList.map(api => {
      if (api.children) {
        const newApi: ApiSelectTreeItem = {
          value: api.apiId,
          title: api.apiName,
          children: generatorApiTreeData(api.children.filter(childApi => childApi.apiType === '0' || childApi.apiType === '1' || childApi.apiType === '3'))
        };
        return newApi;
      } else {
        const newApi: ApiSelectTreeItem = {
          value: api.apiId,
          title: api.apiName
        };
        return newApi;
      }
    });
  }

  const code = 'api-list';
  const { apiList, loading, apiTypeData, addLoading, updateLoading } = props;
  // apiList过滤掉按钮，只保留接口权限
  const apiTreeData = generatorApiTreeData(apiList);
  const rowKey = (record: ApiItem) => record.apiId;
  const pkField = 'apiId';

  return (
    <PageContainer>
        <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
          <ProCard title='查询条件' headerBordered >
            <ApiQueryForm colon={false} onSubmit={handleFetchApi} loading={loading}/>
          </ProCard>
          <ProCard>
            <AGrid
              code={code}
              btnCallBack={handleBtnCallBack}
              columns={columns}
              rowKey={rowKey}
              pkField={pkField}
              dataSource={apiList}
              loading={loading}
              onSelectRow={onSelectRow}
              scroll={{x:1600}}
              actionColumnFixed={'right'}
            />
          </ProCard>
        </Space>
        {
          !addModalVisible ? null :
          <AddApiModal
            apiTypeData={apiTypeData}
            apiTreeData={apiTreeData}
            colon={false}
            modalTitle='新增接口权限'
            modalWidth={1000}
            modalVisible={addModalVisible}
            loading={addLoading}
            formData={apiFormData}
            onHandlerOK={handleAddModalOk}
            onHandlerCancel={handleAddModalCancel}
          />
        }
        {
          !updateModalVisible ? null :
          <UpdateApiModal
            apiTypeData={apiTypeData}
            apiTreeData={apiTreeData}
            colon={false}
            modalTitle=''
            modalWidth={1000}
            modalVisible={updateModalVisible}
            flag={flag}
            loading={updateLoading}
            formData={apiFormData}
            onHandlerOK={handleUpdateModalOk}
            onHandlerCancel={handleUpdateModalCancel}
          />
        }
    </PageContainer>
  );
}

export default connect(({ apis, loading }: ConnectState) => ({
  ...apis,
  loading: loading.effects['apis/fetchAllApi'],
  addLoading: loading.effects['apis/addApi'],
  updateLoading: loading.effects['apis/updateApi'],
}))(ApiList);